/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.juick.mod;

import com.juick.mod.api.JuickMessage;

import android.view.Menu;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.HeaderViewListAdapter;

import java.net.URLEncoder;

/**
 *
 * @author ugnich
 */
public class MessagesActivity extends ListActivity implements AdapterView.OnItemClickListener, OnScrollListener {

	private static final int MENUITEM_POST = 1;
	private static final int MENUITEM_REFRESH = 2;
	private static final int MENUITEM_EXPLORE = 3;
    private static final int MENUITEM_SETTING = 4;
    private JuickMessagesAdapter listAdapter;
    private View viewLoading;
    private String apiurl;
    private boolean loading = true;
    private int page = 0;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent i = getIntent();
        boolean home = i.getBooleanExtra("home", false);
        int uid = i.getIntExtra("uid", 0);
        int go = i.getIntExtra("go", 0);
        String uname = i.getStringExtra("uname");
        String search = i.getStringExtra("search");
        String tag = i.getStringExtra("tag");
        
        if (go > 0) {
        	onResume();
        	Intent threadIntent = new Intent(this, ThreadActivity.class);
        	threadIntent.putExtra("mid", go);
            startActivity(threadIntent);
            finish();
        } else if (uid > 0 && uname != null) {
            apiurl = "http://api.juick.com/messages?user_id=" + uid;
            setTitle("@" + uname);
        } else if (search != null) {
            try {
                apiurl = "http://api.juick.com/messages?search=" + URLEncoder.encode(search, "utf-8");
            } catch (Exception e) {
                Log.e("ApiURL", e.toString());
            }
            setTitle(getResources().getString(R.string.Search) + ": " + search);
        } else if (tag != null) {
            try {
                apiurl = "http://api.juick.com/messages?tag=" + URLEncoder.encode(tag, "utf-8");
            } catch (Exception e) {
                Log.e("ApiURL", e.toString());
            }
            setTitle(getResources().getString(R.string.Tag) + ": " + tag);
        } else if (home) {
            apiurl = "http://api.juick.com/home?1=1";
            setTitle(getResources().getString(R.string.Messages));
        } else {
            apiurl = "http://api.juick.com/messages?1=1";
            setTitle(getResources().getString(R.string.All_messages));
        }

        getListView().setOnScrollListener(this);
        initAdapter();
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	int oldTheme = MainActivity.theme;
    	int oldSize = MainActivity.avatarSize;
    	
    	SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    	MainActivity.nick = settings.getString("nick", "");
    	MainActivity.password = settings.getString("password", null);
    	MainActivity.round = settings.getBoolean("round", true);
    	MainActivity.textSize = Float.parseFloat(settings.getString("size", "14"));
    	MainActivity.theme = Integer.parseInt(settings.getString("theme", "0")); 
    	MainActivity.loadAvatar = settings.getBoolean("avatar", false);
    	MainActivity.avatarSize = Integer.parseInt(settings.getString("av_size", "32"));
   	    switch (MainActivity.theme) {
   	        case 0: // Default colors
   	        	MainActivity.textColor = 0xFF333333;
   	        	MainActivity.backgroundColor = 0xFFCBCB9C;
   	        	MainActivity.msgBackgroundColor = 0xFFEEEEDF;
   	        	MainActivity.infoBackgroundColor = 0xFFE3E3D3;
   	        	MainActivity.headerTextColor = 0XFFB47329;
   	        	MainActivity.linkTextColor = 0xFFB47329;
   	        	MainActivity.unameTextColor = 0xFF000000;
   	        	MainActivity.infoTextColor = 0xFFB47329;
   	        	MainActivity.dividerHeight = 0;
   	        	MainActivity.textPadding = 9;
   	        	
   	        	MainActivity.ulResId = R.drawable.up_left_default;
   	        	MainActivity.urResId = R.drawable.up_right_default;
   	        	MainActivity.dlResId = R.drawable.down_left_default;
   	        	MainActivity.drResId = R.drawable.down_right_default;
   			    break;
   		    case 1: // Dark-grey colors
   		    	MainActivity.textColor = 0xFFCCCCCC;
   		    	MainActivity.backgroundColor = 0xFF202020;
   		    	MainActivity.msgBackgroundColor = 0xFF383838;
   		    	MainActivity.infoBackgroundColor = 0xFF484848;
   		    	MainActivity.headerTextColor = 0XFFB8833E;
   		    	MainActivity.linkTextColor = 0xFF3C77AA;
   		    	MainActivity.unameTextColor = 0xFFFFFFFF;
   		    	MainActivity.infoTextColor = 0xFF999999;
   		    	MainActivity.dividerHeight = 0;
   		    	MainActivity.textPadding = 9;
   	        	
   		    	MainActivity.ulResId = R.drawable.up_left_dark_grey;
   		    	MainActivity.urResId = R.drawable.up_right_dark_grey;
   		    	MainActivity.dlResId = R.drawable.down_left_dark_grey;
   		    	MainActivity.drResId = R.drawable.down_right_dark_grey;
   		    	break;
   		    case 2: // Black colors
   		    	MainActivity.textColor = 0xFF999999;
   		    	MainActivity.backgroundColor = 0xFF000000;
   		    	MainActivity.msgBackgroundColor = 0x00000000;
   		    	MainActivity.infoBackgroundColor = 0x00000000;
   		    	MainActivity.headerTextColor = 0xFFB47329;
   		    	MainActivity.linkTextColor = 0xFFFFFFFF;
   		    	MainActivity.unameTextColor = 0xFFFFFFFF;
   		    	MainActivity.infoTextColor = 0xFFB47329;
   		    	MainActivity.dividerHeight = 1;
   		    	MainActivity.textPadding = 4;
   		    	MainActivity.round = false;
	        	break;
   		    case 3: // White colors
   		    	MainActivity.textColor = 0xFF333333;
   		    	MainActivity.backgroundColor = 0xFFFFFFFF;
   		    	MainActivity.msgBackgroundColor = 0xFFFFFFFF;
   		    	MainActivity.infoBackgroundColor = 0xFFFFFFFF;
   		    	MainActivity.headerTextColor = 0xFF0030F0;
   		    	MainActivity.linkTextColor = 0xFF0030F0;
   		    	MainActivity.unameTextColor = 0xFF000000;
   		    	MainActivity.infoTextColor = 0xFF0030F0;
   		    	MainActivity.dividerHeight = 1;
   		    	MainActivity.textPadding = 4;
   		    	MainActivity.round = false;
            	break;
   	    }
   	    if (MainActivity.theme != oldTheme | MainActivity.avatarSize != oldSize) {
   	    	initAdapter();
   	    }
    }
    
    private void initAdapter() {
    	getListView().setBackgroundColor(MainActivity.backgroundColor);
    	getListView().setDividerHeight(MainActivity.dividerHeight);
    	getListView().setCacheColorHint(0x00000000);
        getListView().setAdapter(new HeaderViewListAdapter(null, null, null));

        viewLoading = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listitem_loading, null);
        viewLoading.setBackgroundColor(MainActivity.backgroundColor);
        int count = getListView().getCount();
        if (count < 1) {
        	getListView().addFooterView(viewLoading, null, false);
        }

        listAdapter = new JuickMessagesAdapter(this);
        getListView().setAdapter(listAdapter);

        getListView().setOnItemClickListener(this);
        getListView().setOnItemLongClickListener(new JuickMessageMenu(this));
        
        Thread thr = new Thread(new Runnable() {

            public void run() {
                final String jsonStr = MainActivity.getJSON(MessagesActivity.this, apiurl);
                MessagesActivity.this.runOnUiThread(new Runnable() {

                    public void run() {
                        if (jsonStr == null || listAdapter.parseJSON(jsonStr) != 20) {
                            MessagesActivity.this.getListView().removeFooterView(viewLoading);
                        }
                        loading = false;
                    }
                });
            }
        });
        thr.start();
    }

    //@Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (visibleItemCount < totalItemCount && (firstVisibleItem + visibleItemCount == totalItemCount) && loading == false) {
            loading = true;
            page++;
            final JuickMessage jmsg = (JuickMessage) listAdapter.getItem(listAdapter.getCount() - 1);

            Thread thr = new Thread(new Runnable() {

                public void run() {
                    final String jsonStr = MainActivity.getJSON(MessagesActivity.this, apiurl + "&before_mid=" + jmsg.MID + "&page=" + page);
                    MessagesActivity.this.runOnUiThread(new Runnable() {

                        public void run() {
                            if (jsonStr == null || listAdapter.parseJSON(jsonStr) != 20) {
                                MessagesActivity.this.getListView().removeFooterView(viewLoading);
                            }
                            loading = false;
                        }
                    });
                }
            });
            thr.start();
        }
    }

    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        JuickMessage jmsg = (JuickMessage) parent.getItemAtPosition(position);
        Intent i = new Intent(this, ThreadActivity.class);
        i.putExtra("mid", jmsg.MID);
        startActivity(i);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (menu.findItem(MENUITEM_POST) == null) {
            menu.add(Menu.NONE, MENUITEM_POST, Menu.NONE, R.string.Post).setIcon(android.R.drawable.ic_menu_edit);
        }
        if (menu.findItem(MENUITEM_REFRESH) == null) {
            menu.add(Menu.NONE, MENUITEM_REFRESH, Menu.NONE, R.string.Refresh).setIcon(android.R.drawable.ic_menu_rotate);
        }
        if (menu.findItem(MENUITEM_EXPLORE) == null) {
            menu.add(Menu.NONE, MENUITEM_EXPLORE, Menu.NONE, R.string.Explore).setIcon(android.R.drawable.ic_menu_search);
        }
        if (menu.findItem(MENUITEM_SETTING) == null) {
            menu.add(Menu.NONE, MENUITEM_SETTING, Menu.NONE, R.string.Settings).setIcon(android.R.drawable.ic_menu_preferences);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	    case MENUITEM_POST:
	    	    Intent postIntent = new Intent(this, NewMessageActivity.class);
        	    startActivity(postIntent);
	    	    break;
    	    case MENUITEM_REFRESH:
    	    	initAdapter();
    	    	break;
    	    case MENUITEM_EXPLORE:
    	    	Intent exploreIntent = new Intent(this, ExploreActivity.class);
            	startActivity(exploreIntent);
            	break;
    	    case MENUITEM_SETTING:
    	    	Intent settingIntent = new Intent(this, PreferencesActivity.class);
    	    	startActivity(settingIntent);
    	    	break;
    	    default:
    	    	return false;
    	}
    	return true;
    }
}
